<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

/**
 * Submit form action - external email address to forward selected emails to.
 * see: SBCCMCP28
 * http://tracker.remote-learner.net/browse/SBCCMCP-28
 *
 * @package   block_email_list
 * @author    Brent Boghosian <brent.boghosian@remote-learner.net>
 * @copyright 2011 Remote Learner - http://www.remote-learner.net
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
require_once('../../../config.php');
require_once($CFG->dirroot.'/lib/weblib.php');
require_once($CFG->dirroot.'/blocks/email_list/email/lib.php');
require_once($CFG->dirroot.'/blocks/email_list/email/email.class.php');

// AJAX functions
require_once($CFG->libdir. '/ajax/ajaxlib.php');

$courseid = required_param('courseid', PARAM_INT);
$mailidlist = required_param('mailids', PARAM_SEQUENCE);
$mailids = explode(',', $mailidlist);
$emailto = required_param('emailto', PARAM_TEXT);
$emailaddrs = explode(',', $emailto);

global $USER;

foreach ($emailaddrs as $emailaddr) {

    if (!validate_email($emailaddr)) {
        $addrerror = 1;
        break;
    }
}

$email2ext_url = $CFG->wwwroot ."/blocks/email_list/email/email2ext.php{$courseid}&mailids={$mailidlist}";

if (isset($addrerror)) {
    // Invalid email address; alert and return to previous page
    echo "<script type=\"text/javascript\">\n//<![CDATA[\n"
        ."alert('". $emailaddr . get_string('invalidemail', 'block_email_list') ."');\n"
        ."this.location = '{$email2ext_url}';\n//]]>\n</script>";
    return;
}

require_login($courseid, false); // No autologin guest

if ( !email_is_enabled_email_list($courseid) ) {
    print_error('blocknotavailable', 'block_email_list');
}

$context = context_course::instance($courseid);

if (!$course = $DB->get_record('course', array('id' => $courseid))) {
    print_error('invalidcourseid', 'block_email_list');
}

if ( !$course->visible && !has_capability('moodle/course:viewhiddencourses', $context, $USER->id, false) ) {
    print_error('courseavailablenot', 'moodle');
}

$PAGE->set_title(get_string('forwardtoexternal', 'block_email_list'));
$PAGE->requires->css('blocks/email_list/email/email.css');

echo $OUTPUT->header();

echo "<br />\n";
echo get_string('sendingemail', 'block_email_list');

unset($user);
$addrerror = 0;

foreach ($mailids as $mailid) {

    if (!isset($user)) {
        $user = $USER;
    }

    if ($mail = $DB->get_record('block_email_list_mail', array('id' => $mailid))) {
        $email = new eMail();
        $email->set_email($mail);
        $email->attachments = $email->get_attachments();
        // MUST get attachments before re-assigning userid!
        $email->userid = $user->id;
        $email->writer = $user->id;
        $email->set_subject(addslashes(get_string('fw', 'block_email_list') ." $email->subject"));
        // TBD: clear/flag To/CC/Bcc value(s)
        $email->to = null;
        $email->cc = null;
        $email->bcc = null;

        $email->timecreated = time();

        /* ***
         $mail->respondedid = ?
         // TBD: Add '>' to start of each line in body of message - forward
         $lines = explode('<br />', $email->body);
         $body = email_make_default_line_replyforward($user,
         $email->timecreated, $context);
         foreach($lines as $line) {
         $body = $body. '>' .$line. '<br />'."\n";
         }
         $email->body = $body;
         *** */
        $email->body = addslashes($mail->body);

        // Insert Email into block_email_list_mail table
        $email->insert_mail_record(); // must call private method

        $errorstr = '';

        if (! sendmail_external($emailaddrs, $user, $email->subject, $mail->body, $email->attachments, $errorstr)) {
            $addrerror++;
            // remove inserted mail record - check for error (TBD)?
            $DB->delete_records('block_email_list_mail', array('id' => $email->id));
            add_to_log($email->course, 'email_list', 'forward ext.', '',
                       "ERROR: {$errorstr}", 0, $email->userid);
        } else {
            // log the email sending
            add_to_log($email->course, 'email_list', 'forward ext.', '',
                       "$email->subject", 0, $email->userid);

            if ( !insert_external_list_send($email, $emailto) ) {
                print_error('failinsertrecord', 'block_email_list', $email2ext_url);
            }

            // copy forwarded email to 'Sent Items' folder
            // and update table: block_email_list_foldermail
            if ( !$email->reference_mail_folder($email->userid, EMAIL_SENDBOX) ) {
                print_error('failupdatefolder', 'block_email_list', $email2ext_url);

            } else if (!empty($email->attachments) ) {
                $srcpath = $CFG->dataroot .'/'. $attach->path;

                if (! ($destpath = $email->get_file_area())) {
                    print_error('failcopingattachments', 'block_email_list', $destpath);
                }

                // copy attachments
                foreach ($email->attachments as $attach) {

                    if (!copy("{$srcpath}/{$attach->name}", "{$destpath}/{$attach->name}") ) {
                        print_error('failcopingattachments', 'block_email_list',
                                    "{$srcpath}/{$attach->name} => {$destpath}/{$attach->name}");
                    }
                }
            }
        }
    } else {
        print_error('failgetmail', 'block_email_list');
    }
}

echo "<script type=\"text/javascript\">\n//<![CDATA[\nalert('"
   . get_string(($addrerror > 0) ? 'failsendext' : 'emailextsuccess', 'block_email_list')."');\n";

if ($addrerror == 0) {
    echo "this.close();\n";
}
echo "//]]>\n</script>\n<br />";

echo $OUTPUT->footer();
